﻿/**
* jQuery EasyUI 1.4.3
* Copyright (c) 2009-2015 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
* To use it on other terms please contact us at info@jeasyui.com
* http://www.jeasyui.com/license_commercial.php
*
* jQuery EasyUI datagrid 组件扩展
* jeasyui.extensions.datagrid.columnSelector.js
* 开发 落阳
* 最近更新：2018-02-09
*
* 依赖项：
*   1、jquery.jdirk.js
*   2、jeasyui.extensions.datagrid.getColumnInfo.js
*   3、jeasyui.extensions.selector.dblDatagrid.js
*/
(function ($) {

    $.util.namespace("$.fn.datagrid.extensions");

    var globalDefaults = {
        columnSelectorCacheName: "showColumnsBySelector"
    };

    function isMultiLineHeaders(target) {
        var state = $.data(target, "datagrid"),
            opts = state.options;
        if (opts.columns && opts.columns.length > 1 && opts.columns[0].length && opts.columns[1].length) {
            return true;
        }
        if (opts.frozenColumns && opts.frozenColumns.length > 1 && opts.frozenColumns[0].length && opts.frozenColumns[1].length) {
            return true;
        }
        return false;
    }

    var openColumnSelector = function (target, frozen) {
        var t = $(target), state = $.data(target, "datagrid"), opts = state.options;

        ////检查是否为复合列
        //if (state.multiLineHeaders) {
        //    $.error("不支持在多行表头情况下执行列配置的操作。");
        //}

        var configableColumns = getAllConfigableColumn(target, frozen);
        var columnData = $.array.map(configableColumns, function (item) {
            return { columnField: item.field, columnName: item.title };
        });

        var selectedData = $.array.map(state[globalDefaults.columnSelectorCacheName] || [], function (item) {
            return item.columnField;
        });

        var selector = $.easyui.showSelector.dblDatagrid({
            width: 700,
            height: 430,
            title: "数据列选择器",
            datagridOptions: {
                idField: "columnField",
                singleSelect: false,
                columns: [[
                { field: "columnField", title: "列字段", width: 120 },
                { field: "columnName", title: "列名称", width: 150 }
                ]],
                data: columnData
            },
            selected: selectedData,
            selectedAllowMove: true,
            onEnter: function (selected) {
                console.log("选择列：");
                console.log(selected);

                //检查选择的列是否存在“跨列”的列
                for (var i = 0; i < selected.length; i++) {
                    var flag = t.datagrid("isCrossMultiFields", selected[i].columnField);
                    if (flag) {
                        $.messager.alert("操作提醒", "列[" + selected[i].columnField + " - " + selected[i].columnName + "]属于“跨多列”的情况，无法进行配置操作，请重新选择。");
                        return;
                    }
                }

                $.array.forEach(configableColumns, function (item) {
                    t.datagrid("hideColumn", item.field);
                });

                $.array.forEach(selected, function (item) {
                    t.datagrid("showColumn", item.columnField);
                });

                //按 selected 的顺序对列进行排序
                sortColumns(target, selected);

                state[globalDefaults.columnSelectorCacheName] = selected;
            }
        });

        return selector;
    };

    var sortColumns = function (target, columnFields) {
        var t = $(target);
        //selected: ACBD
        //real: ABCD
        var allColumns = t.datagrid("getColumnOptions", "all");
        //所有动态列
        var dynamicColumns = $.array.filter(allColumns, function (val) { return val.dynamic; });
        //所有显示的动态列
        var visibleColumns = $.array.filter(dynamicColumns, function (val) { return !val.hidden; });
        //console.log("当前显示的动态列：");
        //console.log(visibleColumns);

        var theFirstVisibleColumnField = undefined;
        var sortInfo = [];
        $.array.forEach(visibleColumns, function (item, sourceIndex) {
            if (!theFirstVisibleColumnField) { theFirstVisibleColumnField = item.field; }
            var targetIndex = $.array.indexOf(columnFields, item.field, 0, columnFields.length, function (item1, item2) { return item1.columnField == item2; });
            //console.log("当前显示的动态列[" + item.field + "][" + item.title + "]在 selected 中的顺序为：" + targetIndex);
            //console.log("当前显示的动态列[" + item.field + "][" + item.title + "]在 当前显示的动态列 中的顺序为：" + sourceIndex);
            sortInfo.push({ field: item.field, title: item.title, sourceIndex: sourceIndex, targetIndex: targetIndex });
        });
        //按 targetIndex 进行排序
        for (var i = 0; i < sortInfo.length - 1; i++) {
            for (var j = 0; j < sortInfo.length - i - 1; j++) {
                if (sortInfo[j].targetIndex > sortInfo[j+1].targetIndex) {
                    var temp = sortInfo[j];
                    sortInfo[j] = sortInfo[j + 1];
                    sortInfo[j + 1] = temp;
                }
            }
        }
        console.log(sortInfo);

        $.array.forEach(sortInfo, function (item) {
            var source = $.array.first(sortInfo, function (value, index) { return value.sourceIndex == item.targetIndex; });
            var point = item.targetIndex < source.targetIndex ? "before" : "after";
            console.log("动态列[" + item.field + "][" + item.title + "]要放到[" + source.field + "][" + source.title + "]的" + point);
            t.datagrid("moveColumn", { source:item.field, target:source.field, point: point, force: true });
        });
    };

    var getAllConfigableColumn = function (target, frozen) {
        var t = $(target), state = $.data(target, "datagrid"), opts = state.options;

        return $.array.filter(state.originalFixedColumnOptions, function (item) { return item.field && item.configable; });
    };

    // 初始化列 options 扩展属性
    function initExtendColumnOptions(t, opts) {
        var target = t[0],
            state = $.data(target, "datagrid"),
            cols = t.datagrid("getColumnOptions", "all");
        $.each(cols, function (i, col) {
            $.union(col, $.fn.datagrid.extensions.columnOptions);
        });
        //缓存原始列
        var allColumnOptions = t.datagrid("getColumnOptions", "all");
        state.originalFixedColumnOptions = $.array.map(allColumnOptions, function (col) {
            return $.extend({}, col);
        });
        state.multiLineHeaders = isMultiLineHeaders(target);
    }

    function initializeExtensions(target) {
        var t = $(target),
            state = $.data(target, "datagrid"),
            opts = state.options;

        initExtendColumnOptions(t, opts);
    }


    var _datagrid = $.fn.datagrid;
    $.fn.datagrid = function (options, param) {
        if (typeof options == "string") {
            return _datagrid.apply(this, arguments);
        }
        options = options || {};
        return this.each(function () {
            var jq = $(this),
                isInited = $.data(this, "datagrid") ? true : false,
                opts = isInited ? options : $.extend({},
                        $.fn.datagrid.parseOptions(this),
                        $.parser.parseOptions(this, []), options);
            _datagrid.call(jq, opts, param);
            if (!isInited) {
                initializeExtensions(this);
            }
        });
    };
    $.union($.fn.datagrid, _datagrid);

    var columnOptions = {

        // 表示该列是否允许配置，其值可以是 Boolean 类型；
        // 默认为 true。
        // 该属性用于在“列选择器”时判定
        configable: true
    };
    if ($.fn.datagrid.extensions.columnOptions) {
        $.extend($.fn.datagrid.extensions.columnOptions, columnOptions);
    }
    else {
        $.fn.datagrid.extensions.columnOptions = columnOptions;
    }


    var methods = {

        //  扩展 easyui-datagrid 的自定义方法；快速打开一个选择器，该选择器中的选择项为 easyui-datagrid 所有列中 configable 属性为 true 的列组成的一个数组集合；参数 frozen 可以定义为如下格式：
        //      Boolean 类型值：如果是 true，则表示打开的选择器里的选择项中要包含 frozen(冻结)列，如果是 false 则表示选择项中不包含 frozen(冻结)列；
        //      String 类型值：如果该参数定义为任意 String 类型值，则包含所有列信息(包括 frozen 冻结列和非冻结列)；
        //  返回值：返回表示 列选择器 的 easyui-dialog 组件的 jQuery 链式对象。
        openColumnSelector: function (jq, frozen) { return openColumnSelector(jq[0], frozen); }
    };

    var defaults = {

    };

    if ($.fn.datagrid.extensions.defaults) {
        $.extend($.fn.datagrid.extensions.defaults, defaults);
    } else {
        $.fn.datagrid.extensions.defaults = defaults;
    }

    if ($.fn.datagrid.extensions.methods) {
        $.extend($.fn.datagrid.extensions.methods, methods);
    } else {
        $.fn.datagrid.extensions.methods = methods;
    }

    $.extend($.fn.datagrid.defaults, defaults);
    $.extend($.fn.datagrid.methods, methods);

})(jQuery);